<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests;
use Illuminate\Support\Facades\Hash;
use View;
use App\Model\User;
use App\Model\UserGroup;

class UserController extends AdminBaseController
{
    public function __construct()
    {
        $option = ['module_name'=>'user','status'=>'user_status'];
        $this->setModelObj(new User,$option);
    }

    /**
     * 获取正确的排序组合
     */
    protected function getTrueOrder($data)
    {
        $orderby = [];
        if(!array_key_exists('sort',$data)){
            $orderby['field'] = $this->model_keyname;
            $orderby['type'] = 'desc';
        }else{
            switch ($data['sort']){
                case 'user_status_format':
                    $orderby['field'] = 'user_status';break;
                case 'user_last_login_time_format':
                    $orderby['field'] = 'user_last_login_time';break;
                default:
                    $orderby['field'] = $data['sort'];break;
            }
            $orderby['type'] =  $data['order'];
        }
        return $orderby;
    }

	/**
	 * 后台管理员添加页面
	 */
	public function addDataView()
	{
		$usergroup = UserGroup::where('usergroup_status',1)->get();
		return View::make('admin.user.useradd',['usergroup'=>$usergroup]);
	}
	
	/**
	 * 后台管理员添加保存
	 */
	public function toAddData(Requests\UserAddRequest $request)
	{
		$data = $request->except(['_token','_method']);
		if($request->get('user_group')){
			$data['user_group'] = ','.implode(',',$data['user_group']).',';
		}
		$data['user_password'] = Hash::make(md5($data['user_password']));
		$data['user_status'] = 1;
		$data['user_add_time'] = time();
		$data['user_add_ip'] = $request->getClientIp();
		$data['user_edit_time'] = time();
		$data['user_edit_ip'] = $request->getClientIp();
		$re = User::insert($data);
        $jsonData = $re ? $this->getJsonData(2,'增加成功') : $this->getJsonData(0,'增加失败');
		return response()->json($jsonData);
	}
	
	/**
	 * 后台管理员编辑页面
	 */
	public function updateDataView($userid)
	{
		$usergroup = UserGroup::where('usergroup_status',1)->get();
		$user_info = User::find($userid);
		return View::make('admin.user.useredit', ['userinfo'=>$user_info,'usergroup'=>$usergroup]);
	}
	
	/**
	 * 后台管理员编辑保存
	 */
	public function toUpdateData(Requests\UserEditRequest $request, $userid)
	{
		$data = $request->except(['_token','_method']);
		if($request->get('user_password')){
			$data['user_password'] = Hash::make(md5($data['user_password']));
		}else{
			unset($data['user_password']);
		}
		if($request->get('user_group')){
			$data['user_group'] = ','.implode(',',$data['user_group']).',';
		}
		$data['user_edit_time'] = time();
		$data['user_edit_ip'] = $request->getClientIp();
		$re = User::where('user_id',$userid)->update($data);
        $jsonData = $re ? $this->getJsonData(2,'编辑成功') : $this->getJsonData(0,'编辑失败');
		return response()->json($jsonData);
	}
}